#include "widget.h"
#include <QApplication>
#include <QStyle>
#include <QPainter>
#include <QPainterPath>
#include <QFontMetrics>
#include <QScrollBar>
#include <QPropertyAnimation>
#include <QGraphicsOpacityEffect>

// ChatBubble 实现
ChatBubble::ChatBubble(const QString &message, bool isOwnMessage, QWidget *parent)
    : QWidget(parent), messageText(message), isOwn(isOwnMessage)
{
    setFixedHeight(40);
    setMinimumWidth(100);
    
    messageLabel = new QLabel(message, this);
    messageLabel->setWordWrap(true);
    messageLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    messageLabel->setStyleSheet(QString(
        "QLabel {"
        "   background-color: %1;"
        "   border-radius: 15px;"
        "   padding: 8px 12px;"
        "   color: %2;"
        "   font-size: 14px;"
        "   max-width: 200px;"
        "}"
    ).arg(isOwn ? "#007AFF" : "#E5E5EA", isOwn ? "white" : "black"));
    
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(5, 5, 5, 5);
    
    if (isOwn) {
        layout->addStretch();
        layout->addWidget(messageLabel);
    } else {
        layout->addWidget(messageLabel);
        layout->addStretch();
    }
}

void ChatBubble::setMessage(const QString &message)
{
    messageText = message;
    messageLabel->setText(message);
}

QString ChatBubble::getMessage() const
{
    return messageText;
}

// ChatWidget 实现
ChatWidget::ChatWidget(const QString &userName, const QString &avatarColor, QWidget *parent)
    : QWidget(parent), userName(userName), avatarColor(avatarColor)
{
    setMinimumSize(300, 400);
    
    // 主布局
    mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    
    // 头部布局（头像和用户名）
    headerLayout = new QHBoxLayout();
    headerLayout->setSpacing(10);
    
    // 圆形头像
    avatarLabel = new QLabel(this);
    avatarLabel->setFixedSize(40, 40);
    avatarLabel->setStyleSheet(QString(
        "QLabel {"
        "   background-color: %1;"
        "   border-radius: 20px;"
        "   color: white;"
        "   font-weight: bold;"
        "   font-size: 16px;"
        "   qproperty-alignment: AlignCenter;"
        "}"
    ).arg(avatarColor));
    avatarLabel->setText(userName.left(1).toUpper());
    
    // 用户名
    userNameLabel = new QLabel(userName, this);
    userNameLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: bold; color: #333; }");
    
    headerLayout->addWidget(avatarLabel);
    headerLayout->addWidget(userNameLabel);
    headerLayout->addStretch();
    
    mainLayout->addLayout(headerLayout);
    
    // 消息列表
    messageList = new QListWidget(this);
    messageList->setStyleSheet(
        "QListWidget {"
        "   background-color: #F2F2F7;"
        "   border: none;"
        "   border-radius: 10px;"
        "}"
        "QListWidget::item {"
        "   background-color: transparent;"
        "   padding: 2px;"
        "}"
    );
    messageList->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    messageList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    
    mainLayout->addWidget(messageList);
    
    // 输入区域
    inputLayout = new QHBoxLayout();
    inputLayout->setSpacing(10);
    
    inputEdit = new QLineEdit(this);
    inputEdit->setPlaceholderText("输入消息...");
    inputEdit->setStyleSheet(
        "QLineEdit {"
        "   border: 2px solid #E5E5EA;"
        "   border-radius: 20px;"
        "   padding: 8px 15px;"
        "   font-size: 14px;"
        "   background-color: white;"
        "}"
        "QLineEdit:focus {"
        "   border-color: #007AFF;"
        "}"
    );
    
    sendButton = new QPushButton("发送", this);
    sendButton->setFixedSize(60, 36);
    sendButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #007AFF;"
        "   color: white;"
        "   border: none;"
        "   border-radius: 18px;"
        "   font-size: 14px;"
        "   font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "   background-color: #0056CC;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #004499;"
        "}"
    );
    
    inputLayout->addWidget(inputEdit);
    inputLayout->addWidget(sendButton);
    
    mainLayout->addLayout(inputLayout);
    
    // 正在输入指示器
    typingIndicator = new QLabel("正在输入中...", this);
    typingIndicator->setStyleSheet(
        "QLabel {"
        "   color: #8E8E93;"
        "   font-size: 12px;"
        "   font-style: italic;"
        "   padding: 5px;"
        "}"
    );
    typingIndicator->hide();
    mainLayout->addWidget(typingIndicator);
    
    // 连接信号和槽
    connect(sendButton, &QPushButton::clicked, this, &ChatWidget::onSendButtonClicked);
    connect(inputEdit, &QLineEdit::textChanged, this, &ChatWidget::onInputTextChanged);
    connect(inputEdit, &QLineEdit::returnPressed, this, &ChatWidget::onSendButtonClicked);
    
    // 输入计时器
    typingTimer = new QTimer(this);
    typingTimer->setSingleShot(true);
    typingTimer->setInterval(1000);
    connect(typingTimer, &QTimer::timeout, [this]() {
        showTypingIndicator(false);
    });
}

void ChatWidget::addMessage(const QString &message, bool isOwnMessage)
{
    ChatBubble *bubble = new ChatBubble(message, isOwnMessage);
    QListWidgetItem *item = new QListWidgetItem(messageList);
    item->setSizeHint(bubble->sizeHint());
    messageList->setItemWidget(item, bubble);
    messageList->addItem(item);
    messageList->scrollToBottom();
}

void ChatWidget::showTypingIndicator(bool show)
{
    if (show) {
        typingIndicator->show();
    } else {
        typingIndicator->hide();
    }
}

void ChatWidget::onSendButtonClicked()
{
    QString message = inputEdit->text().trimmed();
    if (!message.isEmpty()) {
        emit messageSent(message);
        inputEdit->clear();
        showTypingIndicator(false);
        typingTimer->stop();
    }
}

void ChatWidget::onInputTextChanged()
{
    if (!inputEdit->text().isEmpty()) {
        showTypingIndicator(true);
        typingTimer->start();
    } else {
        showTypingIndicator(false);
        typingTimer->stop();
    }
}

// Widget 实现
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle("双用户聊天界面");
    setMinimumSize(800, 600);
    
    // 主布局
    mainLayout = new QHBoxLayout(this);
    mainLayout->setSpacing(20);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 创建两个聊天界面
    leftChat = new ChatWidget("左用户", "#FF6B6B");
    rightChat = new ChatWidget("右用户", "#4ECDC4");
    
    mainLayout->addWidget(leftChat);
    mainLayout->addWidget(rightChat);
    
    // 连接信号
    connect(leftChat, &ChatWidget::messageSent, this, &Widget::onLeftMessageSent);
    connect(rightChat, &ChatWidget::messageSent, this, &Widget::onRightMessageSent);
    
    // 设置窗口样式
    setStyleSheet(
        "QWidget {"
        "   background-color: #F8F9FA;"
        "   font-family: 'Microsoft YaHei', Arial, sans-serif;"
        "}"
    );
}

Widget::~Widget()
{
}

void Widget::onLeftMessageSent(const QString &message)
{
    // 左用户发送消息：在左界面显示为自己的消息，在右界面显示为对方的消息
    leftChat->addMessage(message, true);
    rightChat->addMessage(message, false);
}

void Widget::onRightMessageSent(const QString &message)
{
    // 右用户发送消息：在右界面显示为自己的消息，在左界面显示为对方的消息
    rightChat->addMessage(message, true);
    leftChat->addMessage(message, false);
}
